package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

//设置websocket
//CheckOrigin防止跨站点的请求伪造
var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func Test(ctx *gin.Context) {
	//升级get请求为webSocket协议
	ws_, err := upGrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		return
	}
	defer ws_.Close() //返回前关闭
	for {
		//读取ws中的数据
		mt, message, err := ws_.ReadMessage()
		if err != nil {
			break
		}
		fmt.Println("收到", message)
		m := "写入" + string(message)
		//写入ws数据
		err = ws_.WriteMessage(mt, []byte(m))
		if err != nil {
			break
		}
	}
}
